package com.tepth.busfix.main.login;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.tepth.busfix.R;
import com.tepth.busfix.base.BaseActivity;
import com.tepth.busfix.bean.reponse.User;
import com.tepth.busfix.config.AccountType;
import com.tepth.busfix.config.SpKey;
import com.tepth.busfix.main.home.HomeActivity;
import com.tepth.busfix.main.setting.SettingActivity;
import com.tepth.busfix.tools.ActivityTaskManager;
import com.tepth.busfix.tools.SPUtils;
import com.tepth.busfix.view.dialog.DialogDelegate;
import com.tepth.busfix.view.dialog.SweetAlertDialogDelegate;

import butterknife.BindView;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity implements LoginContract.View {
    @BindView(R.id.layout_logo)
    View layoutLogo;
    @BindView(R.id.login_linearLayout)
    View layoutLogin;
    @BindView(R.id.login_edtPwd)
    EditText etPwd;
    @BindView(R.id.login_edtId)
    EditText etAccount;
    private SweetAlertDialogDelegate dialogDelegate;
    LoginPresenter mPresenter;
    LoginModel mModel;
    private static final int REQUEST_CODE_SD = 2;

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        dialogDelegate = new SweetAlertDialogDelegate(this);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_CODE_SD);
        } else {
            onAutoLogin();
        }
    }

    @Override
    public void setPresenter() {
        mPresenter = new LoginPresenter();
        mModel = new LoginModel();
        mPresenter.setVM(this, mModel);
    }

    @OnClick(R.id.login_btnLogin)
    public void onLogin() {
        mPresenter.login();
        dialogDelegate.showProgressDialog(true, getString(R.string.user_login));
    }

    @Override
    public void onNetworkError(String msg) {
        dialogDelegate.stopProgressWithFailed(msg, msg);
    }

    @Override
    public void onError(String msg) {
        dialogDelegate.stopProgressWithFailed(msg, msg);
    }

    @Override
    public void onTokenInvalid(String msg) {

        dialogDelegate.stopProgressWithFailed(msg, msg);
    }

    @Override
    public String getAccount() {
        return AccountType.ACCOUNT_TYPE + etAccount.getText().toString().trim();
    }

    @Override
    public String getPassword() {
        return etPwd.getText().toString().trim();
    }

    @Override
    public void showUser(User user) {
        try {
            SPUtils.putString(this, SpKey.KEY_AUTH_KEY, user.getAuthKey());
            SPUtils.putObject(this, SpKey.KEY_USER_INFO, user);
            SPUtils.putString(this, SpKey.KEY_USER_ACCOUNT, etAccount.getText().toString().trim());
            SPUtils.putString(this, SpKey.KEY_USER_PASSWORD, etPwd.getText().toString().trim());
            dialogDelegate.clearDialog();
            ActivityTaskManager.getActivityTaskManager().addActivity(this);
            startActivity(new Intent(this, HomeActivity.class));
        } catch (Exception e) {
            e.printStackTrace();
            dialogDelegate.stopProgressWithWarning("登陆失败", "用户信息获取失败!", new DialogDelegate.OnDialogListener() {
                @Override
                public void onClick() {
                    dialogDelegate.clearDialog();
                }
            });
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.onDestroy();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_SD: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    onAutoLogin();
                } else {
                    Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    public void onAutoLogin() {
        String account = SPUtils.getString(this, SpKey.KEY_USER_ACCOUNT, "");
        String password = SPUtils.getString(this, SpKey.KEY_USER_PASSWORD, "");
        if (!account.isEmpty() && !password.isEmpty()) {
            etAccount.setText(account);
            etPwd.setText(password);
            Intent intent = getIntent();
            if (!intent.hasExtra("reload")) {
                ActivityTaskManager.getActivityTaskManager().finishActivity(SettingActivity.class);
                ActivityTaskManager.getActivityTaskManager().finishActivity(HomeActivity.class);
                onLogin();
            } else {
                ActivityTaskManager.getActivityTaskManager().finishActivity(SettingActivity.class);
                ActivityTaskManager.getActivityTaskManager().finishActivity(HomeActivity.class);
            }
        }
    }

}
